package com.example.tiantian.camera;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.example.tiantian.BaseActivity;
import com.example.tiantian.R;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.PictureCallback;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class CameraActivity extends BaseActivity
        implements OnClickListener, OnSeekBarChangeListener, Callback, SensorEventListener {

    SurfaceView svMain;
    SurfaceHolder holder;

    SeekBar barZoom;

    ImageView imgTake;
    ImageView imgFlash;
    ImageView imgBack;

    Bitmap imgBackSrc;
    Bitmap imgTakeSrc;
    Bitmap imgFlashSrc_On;
    Bitmap imgFlashSrc_Off;
    Bitmap imgFlashSrc_Auto;

    Camera camera;
    Parameters parameters;

    int flash_state;
    int maxZoom;
    int zoom;

    SharedPreferences spf;

    /**
     * 传感器管理
     */
    SensorManager sensorManager;
    /**
     * 加速计
     */
    Sensor accelerometer;

    /**
     * 当前屏幕方向
     */
    int orientation;

    /**
     * 屏幕直立
     */
    public static final int ORIENTATION_P = 0;
    /**
     * 屏幕横置
     */
    public static final int ORIENTATION_L = 1;
    /**
     * 屏幕反向直立
     */
    public static final int ORIENTATION_AP = 2;
    /**
     * 屏幕反向横置
     */
    public static final int ORIENTATION_AL = 3;

    @Override
    protected void init() {
        setContentView(R.layout.activity_camera);

        svMain = (SurfaceView) findViewById(R.id.camera_main);
        barZoom = (SeekBar) findViewById(R.id.camera_zoom);
        imgTake = (ImageView) findViewById(R.id.camera_take);
        imgFlash = (ImageView) findViewById(R.id.camera_flash);
        imgBack = (ImageView) findViewById(R.id.camera_back);

        holder = svMain.getHolder();

        // holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

        spf = getSharedPreferences("TianTian", Context.MODE_PRIVATE);

        // 取得服务 设置传感器
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);

        imgBackSrc = BitmapFactory.decodeResource(getResources(), R.drawable.back);
        imgTakeSrc = BitmapFactory.decodeResource(getResources(), R.drawable.photo);
        imgFlashSrc_Auto = BitmapFactory.decodeResource(getResources(), R.drawable.light_auto);
        imgFlashSrc_On = BitmapFactory.decodeResource(getResources(), R.drawable.light_on);
        imgFlashSrc_Off = BitmapFactory.decodeResource(getResources(), R.drawable.light_off);
    }

    /**
     * 设置按钮图标
     */
    private void imageViewSetImage() {
        imgBack.setImageBitmap(imgBackSrc);
        imgTake.setImageBitmap(imgTakeSrc);
        setFlash();
    }

    @Override
    protected void loadData() {
        flash_state = spf.getInt("flash_state", 0);

    }

    @Override
    protected void event() {
        imgBack.setOnClickListener(this);
        imgFlash.setOnClickListener(this);
        imgTake.setOnClickListener(this);

        barZoom.setOnSeekBarChangeListener(this);

        holder.addCallback(this);

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 注册传感器
        sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 注销传感器
        sensorManager.unregisterListener(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Editor editor = spf.edit();
        editor.putInt("flash_state", flash_state);
        editor.commit();
    }

    /**
     * 设置闪光灯
     */
    private void setFlash() {
        switch (flash_state) {
        case 0:
            parameters.setFlashMode(Parameters.FLASH_MODE_AUTO);
            imgFlash.setImageBitmap(imgFlashSrc_Auto);
            break;
        case 1:
            parameters.setFlashMode(Parameters.FLASH_MODE_ON);
            imgFlash.setImageBitmap(imgFlashSrc_On);
            break;
        case 2:
            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            imgFlash.setImageBitmap(imgFlashSrc_Off);
            break;
        default:
            break;
        }
        camera.setParameters(parameters);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (camera != null) {
            camera.release();
        }
        camera = Camera.open();
        parameters = camera.getParameters();
        camera.setDisplayOrientation(90);
        // parameters.set("rotation", 90);

        maxZoom = parameters.getMaxZoom();
        zoom = parameters.getZoom();

        barZoom.setMax(maxZoom);
        barZoom.setProgress(zoom);

        if (parameters.getFlashMode() == null) {
            flash_state = 2;
        }
        setFlash();

        try {
            camera.setPreviewDisplay(holder);
            camera.startPreview();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (camera != null) {
            camera.stopPreview();
            camera.release();
            camera = null;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.camera_back:
            finish();
            break;
        case R.id.camera_flash:
            if (++flash_state == 3) {
                flash_state = 0;
            }
            setFlash();
            break;
        case R.id.camera_take:
            takeAPhoto();
            break;
        default:
            break;
        }
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (fromUser) {
            parameters.setZoom(progress);
            camera.setParameters(parameters);
        }
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
    }

    /**
     * 拍照
     */
    private void takeAPhoto() {
        // 自动对焦
        camera.autoFocus(null);
        // 拍照
        camera.takePicture(null, null, new PictureCallback() {

            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                // 保存
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_UNMOUNTED)) {
                    CameraActivity.this.toast("没有加载SD卡");
                    return;
                }
                File file = new File(Environment.getExternalStorageDirectory(), "TianTianPhoto");
                if (!file.exists()) {
                    file.mkdir();
                }
                file = new File(file, "photo" + System.currentTimeMillis() + ".jpg");
                try {
                    if (!file.exists()) {
                        file.createNewFile();
                    }
                    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
                    BitmapFactory.decodeByteArray(data, 0, data.length).compress(CompressFormat.JPEG, 100, bos);
                    bos.close();

                    Bundle extras = new Bundle();
                    extras.putString("photo", file.getAbsolutePath());
                    CameraActivity.this.startActivity(PhotoActivity.class, extras, false);
                } catch (IOException e) {
                    e.printStackTrace();
                    CameraActivity.this.toast(e.getMessage());
                }
            }
        });
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];// 平放x=0 左侧抬起x减小 右侧抬起x增加
        float y = event.values[1];// 平放y=0 顶部抬起y增加 底部抬起y减小
        int newOrientation = 0;
        if (Math.abs(y) >= Math.abs(x)) {
            if (y >= 5) {
                newOrientation = ORIENTATION_P;
            } else if (y <= -5) {
                newOrientation = ORIENTATION_AP;
            } else {
                newOrientation = orientation;
            }
        } else {
            if (x <= -5) {
                newOrientation = ORIENTATION_AL;
            } else if (x >= 5) {
                newOrientation = ORIENTATION_L;
            } else {
                newOrientation = orientation;
            }
        }
        if (newOrientation != orientation) {
            changeImage(newOrientation);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        // Do nothing
    }

    /**
     * 更换界面图标
     */
    private void changeImage(int newOrientation) {
        Matrix m = new Matrix();
        m.setRotate(90 * (newOrientation - orientation));
        // 旋转按钮图片
        imgBackSrc = Bitmap.createBitmap(imgBackSrc, 0, 0, imgBackSrc.getWidth(), imgBackSrc.getHeight(), m, true);
        imgTakeSrc = Bitmap.createBitmap(imgTakeSrc, 0, 0, imgTakeSrc.getWidth(), imgTakeSrc.getHeight(), m, true);
        imgFlashSrc_Auto = Bitmap.createBitmap(imgFlashSrc_Auto, 0, 0, imgFlashSrc_Auto.getWidth(),
                imgFlashSrc_Auto.getHeight(), m, true);
        imgFlashSrc_On = Bitmap.createBitmap(imgFlashSrc_On, 0, 0, imgFlashSrc_On.getWidth(),
                imgFlashSrc_On.getHeight(), m, true);
        imgFlashSrc_Off = Bitmap.createBitmap(imgFlashSrc_Off, 0, 0, imgFlashSrc_Off.getWidth(),
                imgFlashSrc_Off.getHeight(), m, true);
        imageViewSetImage();
        orientation = newOrientation;
    }
}
